<?php
/*
 * 用户model
*/
namespace app\system\model;
use think\Cache;
use \think\Model;
use \think\db;


class User extends Model
{
  protected static $tb = [
	    'shop'    => 'shop',
	    'user'    => 'user',
	    'member'  => 'member',
	    'role'  => 'role', 
      'message'=>'message',
      'order' =>'order',
      'product' =>'product',
      'user_flow' =>'user_flow',
      'user_flow_log' =>'user_flow_log',
      
      
  ]; 

	/*
	* 获取店铺列表
	*@param data
	*@return array
	*/
  public function getShopList($data=[]){
  	$data['page'] = isset($data['page'])?$data['page']:1;
  	$data['rows'] = isset($data['rows'])?$data['rows']:10;
  	$where["s.ischeck"] = $data['ischeck']; //审核已通过
  	$where["s.del_status"] = 0; //未删除
  	if(isset($data['name']) && !empty($data['name'])){
  		$where['s.name'] = ["like","%{$data['name']}%"];
  	}
    $field = "s.id,u.username,u.pid,u.phone,s.name,s.province,s.city,s.district";
    $list['total']=Db::name(self::$tb['shop'])->alias("s")->join("jun_user u","u.id=s.uid")->where($where)->count();
  	$list['list']=Db::name(self::$tb['shop'])->alias("s")->join("jun_user u","u.id=s.uid")
    ->where($where)->field($field)->page($data['page'],$data['rows'])->select();
  	foreach ($list['list'] as $key => $value) { 
  	   $list['list'][$key]['manage_num'] = Db::name(self::$tb['user'])->where(['shop_id'=>$value['id'],'enable'=>1])->count();
  	}
    return $list;
  }


  /*
	* 获取店铺详情
	*@param data
	*@return Object
	*/
  public function getShopDetail($data=[]){
    $where = ['id'=>$data['id'],"del_status"=>0];
    $info = Db::name(self::$tb['shop'])->where($where)->find();
    $field = "u.name,u.phone";
    $shop_admin = Db::name(self::$tb['user'])->alias("u")->join("jun_member m",'m.user_id=u.id')->where(['u.id'=>$info['uid']])->field($field)->find();
    $info['user_name'] = $shop_admin['name'];
    $info['user_phone'] = $shop_admin['phone'];
    return $info;
  }  
 
  /*
	* 审核店铺
	*@param data
	*@return Object
	*/
  public function commitShop($data=[]){
    $where = ['id'=>$data['id'],"del_status"=>0];
    $field = "*";
    $info = Db::name(self::$tb['shop'])->where($where)->find();
    if(!$info){
    	return -10023;
    }
    $update = [
    	"commit_reasion"=>$data['commit_reasion'],
    	"ischeck"=>$data['status'],
    	"commit_id"=>$data['user_id'],
    	"commit_time"=>time()
    ];
    $result = Db::name(self::$tb['shop'])->where("id",$data['id'])->update($update);
    if($result){
       //发送消息通知
    	$content= "审核状态".$data['status']==1?"通过":"不通过";
    	$this->sendMessage(1,$info['uid'],"审核信息",$content.$data['commit_reasion']);
       return true;
    }else{
    	return -10013;
    }
    
  }  
 

  /*
	* 删除店铺
	*@param data
	*@return Object
	*/
  public function deleteShop($data=[]){
    $where = ['id'=>$data['id']];
    $field = "*";
    $info = Db::name(self::$tb['shop'])->where($where)->find();
    if(!$info){
    	return -10023;
    }
    $update['del_status'] = 1;
    $result = Db::name(self::$tb['shop'])->where("id",$data['id'])->update($update);
    if($result){ 
       return true;
    }else{
       return -10013;
    } 
  }  

 
	/*
	* 获取业务经理列表
	*@param data
	*@return array
	*/
  public function getManagerList($data=[]){
  	$data['page'] = isset($data['page'])?$data['page']:1;
  	$data['rows'] = isset($data['rows'])?$data['rows']:10;
    $start = date('Y-m-d 00:00:00');
    $end = date('Y-m-d H:i:s');
  	$where = [
  		"u.enable"=>1,
  	    "u.shop_id"=>$data["shop_id"],
  	    "u.ischeck"=>isset($data["ischeck"])?$data["ischeck"]:1,
        "u.del_status"=>0
    ]; 
    //姓名查询
  	if(isset($data['name']) && !empty($data['name'])){
  		$where['u.name'] = ["like","%{$data['name']}%"];
  	}
  	//手机查询
  	if(isset($data['phone']) && !empty($data['phone'])){
  		$where['u.phone'] = ["like","%{$data['phone']}%"];
  	}
  	$where['r.name'] = "业务经理";
    $field="u.id,u.name,u.username,u.pid,u.phone,u.identify,u.identify_picp,u.identify_picb,u.province,u.city,u.district,u.ischeck,u.join_money,u.addtime,u.sale_total,u.flow_money,r.name as role_name"; 
  	$list=Db::name(self::$tb['user'])->alias("u")->join("jun_role r","u.role_id=r.id")
  	->where($where)->field($field)->page($data['page'],$data['rows'])->select();
    $result['total'] = Db::name(self::$tb['user'])->alias("u")->join("jun_role r","u.role_id=r.id")->where($where)->count();
  	foreach ($list as $key => $value) {
  	   $list[$key]['sale_num'] = Db::name(self::$tb['user'])->where(['pid'=>$value['id'],'enable'=>1])->count();
       $list[$key]['sale_total'] = Db::name(self::$tb['order'])->where(['uid'=>$value['id'],'addtime'=>["between",[$start,$end]],'status'=>['in','1,2']])->sum("paid_price");
  	}
    $result['list'] = $list;
    return $result;
  }

	/*
	* 获取业务经理详情
	*@param data
	*@return array
	*/
   public function getManagerDetail($data=[]){
   	 $field="u.id,u.name,pid,u.phone,u.identify,u.identify_picp,u.identify_picb,
     u.province,u.city,u.district,u.detail,u.join_money,u.sale_total,u.flow_money,
     r.name as role_name,s.name as shop_name"; 
   	 $info = Db::name(self::$tb['user'])->alias("u")
     ->join("jun_role r","r.id = u.role_id","left")
     ->join("jun_shop s","s.id =u.shop_id","left")
     ->where("u.id",$data['id'])->field($field)->find();
   	 if($info){
   	 	return $info;
   	 }else{
   	 	return -10017;
   	 } 
   }

  /*
    * 获取业务经理审核
    *@param data
    *@return array
    */
    public function commitManager($data=[]){  
      $where = ['id'=>$data['id'],"del_status"=>0];
      $field = "*";
      $info = Db::name(self::$tb['user'])->where($where)->find();
      if(!$info){
        return -10023;
      }
      $update = [ 
        "ischeck"=>$data['status'],
        "commit_id"=>$data['user_id'],
        "commit_time"=>time()
      ];
      $result = Db::name(self::$tb['user'])->where("id",$data['id'])->update($update);
      if($result){
        //发送消息通知
        $content= "审核状态".$data['status']==1?"通过":"不通过";
        $this->sendMessage(1,$data['id'],"审核信息",$content);
        return true;
      }else{
          return -10013;
      } 
    }

 
  /*
  * 删除业务经理
  *@param data
  *@return Object
  */
  public function managerDelete($data=[]){
    $where = ['id'=>$data['id']];
    $field = "*";
    $info = Db::name(self::$tb['user'])->where($where)->find();
    if(!$info){
      return -10023;
    }
    $update['del_status'] = 1;
    $result = Db::name(self::$tb['user'])->where("id",$data['id'])->update($update);
    if($result){ 
       return true;
    }else{
       return -10017;
    } 
  }  


  /*
  * 获取业务经理下面的业务员列表
  *@param data
  *@return array
  */
  public function getSaleList($data=[]){
    $data['page'] = isset($data['page'])?$data['page']:1;
    $data['rows'] = isset($data['rows'])?$data['rows']:10;
    $start = date('Y-m-d 00:00:00');
    $end = date('Y-m-d H:i:s');
    $where = [
      "enable"=>1,
      "pid"=>$data["manager_id"],
      "ischeck"=>$data["ischeck"],
      "del_status"=>0
    ]; 
    //姓名查询
    if(isset($data['name']) && !empty($data['name'])){
      $where['name'] = ["like","%{$data['name']}%"];
    }
    //手机查询
    if(isset($data['phone']) && !empty($data['phone'])){
      $where['phone'] = ["like","%{$data['phone']}%"];
    } 
    $field="id,name,username,pid,phone,identify,identify_picp,identify_picb,province,city,district,ischeck,join_money,sale_total,flow_money"; 
    $list=Db::name(self::$tb['user'])->where($where)->field($field)->page($data['page'],$data['rows'])->select();
    $result['total']=Db::name(self::$tb['user'])->where($where)->count();
    foreach ($list as $key => $value) {
       $list[$key]['sale_total'] = Db::name(self::$tb['order'])->where(['uid'=>$value['id'],'addtime'=>["between",[$start,$end]],'status'=>['in','1,2']])->sum("paid_price");
    }
    $result['list'] = $list;
    return $result;
  }

 
  /*
  * 获取业务详情
  *@param data
  *@return array
  */
   public function getSaleDetail($data=[]){
     $field="id,name,username,pid,phone,identify,identify_picp,identify_picb,province,city,district,ischeck,join_money,sale_total,flow_money"; 
     $info = Db::name(self::$tb['user'])->where("id",$data['id'])->field($field)->find();
     if($info){
      $list['order_num'] = Db::name(self::$tb['order'])->where(["uid"=>$info['id']])->count();
      return $info;
     }else{
      return -10017;
     }   
   }




  public function edit_member($data=[]){
    // $data['member_id'] = $data['member_id'];
    $cs_info = Db::name(self::$tb['member'])->where('id',$data['member_id'])->field('id,cs_id,shop_id')->find();
    if(!$cs_info){
      return -10039;
    }
    $data['pid'] = $cs_info['cs_id'];
      $insert = [
        "name" =>$data['name'],
        "phone" =>$data['phone'],
        "shop_id" =>$cs_info['shop_id'],
        "identify_picp" =>$data['identify_picp'],
        "identify_picb" =>$data['identify_picb'],
        "identify" =>$data['identify'],
        "pid" =>0,
        "province" =>$data['province']??"",
        "city" =>$data['city']??"",
        "district" =>$data['district']??"",
        "detail" =>$data['detail']??"",
        "join_money" =>$data['join_money']??0,
        "role_id" =>1,
        "is_user" =>1,
        "user_id" =>$data['member_id'],
        "addtime"=>time(),
      ];
     Db::startTrans();
     try{
      if($data['role_type'] == 1){  //申请加盟商
         $result = Db::name(self::$tb['user'])->insertGetId($insert);
          $insert_shop = [
            "name" =>$data['name'],
            "phone" =>$data['phone'],
            "uid" =>$result,
            "province" =>$data['province']??"",
            "city" =>$data['city']??"",
            "business_card" =>$data['business_card'],
            "business_pic" =>$data['business_pic'],
            "district" =>$data['district']??"",
            "detail" =>$data['detail']??"",
          ];
          $shop = Db::name(self::$tb['shop'])->insertGetId($insert_shop);
          $res = Db::name(self::$tb['user'])->where("id",$result)->update(["shop_id"=>$shop]);
        }else if($data['role_type'] == 2){  
          //申请成为业务经理
          $insert['role_id'] = 2;
          $pid = Db::name(self::$tb['user'])->where("id",$data['pid'])->value('pid');
          $insert['pid'] = $pid??0;
          $res = Db::name(self::$tb['user'])->insert($insert);
        }else if($data['role_type'] == 2){
          //申请成为业务员
          $insert['role_id'] = 3;
          $insert['pid'] = $data['pid'];
          $res = Db::name(self::$tb['user'])->insert($insert);
        }
        Db::commit();
        return true;
      } catch (\Exception $e) {
        Db::rollback();
        //throw($e);
        return -10001;
      } 
    
  }

   
  /*
   *获取分佣列表
   */
   public function saleFlowList($data=[]){ 
    $start = date('Y-m-d 00:00:00');
    $end = date('Y-m-d H:i:s');
    $flow_set =  config("flow_set"); 
    $where = [
      "enable"=>1,
      "pid"=>$data["manager_id"],
      "ischeck"=>$data["ischeck"],
      "del_status"=>0
    ]; 
    $result['shop_flow'] = $flow_set['shop_flow'];
    $result['manager_flow'] = $flow_set['manager_flow'];
    $result['sale_flow'] = $flow_set['sale_flow'];

    $field="u.id,u.name,u.pid,IFNULL(f.shop_flow,0) as shop_flow,IFNULL(f.manager_flow,0) as manager_flow,IFNULL(f.sale_flow,0) as sale_flow"; 
    $list = Db::name(self::$tb['user'])->alias("u")->join("jun_user_flow f","f.user_id=u.id","left")->where($where)->field($field)->select(); 
    foreach ($list as $key => $value) {
      $list[$key]['manager_name'] = Db::name(self::$tb['user'])->where('id',$value['pid'])->value("name");
      $list[$key]['shop_flow'] = $value['shop_flow']!=0?$value['shop_flow']:$flow_set['shop_flow'];
      $list[$key]['manager_flow'] = $value['manager_flow'] !=0?$value['manager_flow']:$flow_set['manager_flow'];
      $list[$key]['sale_flow'] = $value['sale_flow'] !=0?$value['sale_flow']:$flow_set['sale_flow'];
    }
    $result['list'] = $list;
    
    return $result;
   }

   /*
   *设置分佣
   */
   public function saleFlowSet($data=[]){
     $flow_set =  config("flow_set");
     $sale = $data['sale']; 
     $values = $data['values']; 
     $nums = 0;
     for ($i=0; $i < count($sale); $i++) { 
          $exist = Db::name(self::$tb['user_flow'])->where('user_id',$sale[$i])->value('user_id');
          if(($values['manager_flow_'.$sale[$i]]+$values['sale_flow_'.$sale[$i]]+$flow_set['shop_flow']) >1){
             return -10040;
          }
      }
     Db::startTrans();
     try{
        for ($i=0; $i < count($sale); $i++) { 
          $exist = Db::name(self::$tb['user_flow'])->where('user_id',$sale[$i])->value('user_id');
          $save_data = [ 
            'manager_flow' =>$values['manager_flow_'.$sale[$i]],
            'sale_flow' =>$values['sale_flow_'.$sale[$i]]
          ]; 
          if($exist){
             Db::name(self::$tb['user_flow'])->where('user_id',$sale[$i])->update($save_data);
          }else{
              $save_data = [ 
                'user_id' =>$sale[$i],
                'shop_flow'=>$flow_set['shop_flow'],
                'manager_flow' =>$values['manager_flow_'.$sale[$i]],
                'sale_flow' =>$values['sale_flow_'.$sale[$i]],
                'addtime' =>time()
              ]; 
              Db::name(self::$tb['user_flow'])->insert($save_data);
          } 
          $log_insert = [
            "user_id"=>$sale[$i],
            "edit_user"=>$data["uid"],
            'manager_flow' =>$values['manager_flow_'.$sale[$i]],
            'sale_flow' =>$values['sale_flow_'.$sale[$i]],
            "shop_flow"=>$flow_set['shop_flow'],
            "addtime"=>time(),
          ];
           Db::name(self::$tb['user_flow_log'])->insert($log_insert);
        }
        Db::commit();                                                                                                                                             
        return true;
      } catch (\Exception $e) {
        Db::rollback();
        //throw($e);
        return -10001;
      } 
   
   }






















 

    /**     
    * 发送消息
    * @param $type 类型
    * @param $uid 接受消息id
    * @param $message 发送的消息
    */
    public function sendMessage($type,$uid,$title,$message){
        switch($type){
            case 0 : $insert['member_id']=$uid;break;
            case 1 : $insert['uid']=$uid;break;
        } 
        $insert['title'] = $title;
        $insert['content'] = $message;
        $insert['addtime'] = time();
        Db::name(self::$tb['message'])->insert($insert);
    }








}